package com.huaxin.hxcloud.find;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huaxin.common.Constants;
import com.huaxin.common.Entity.FindInfo;
import com.huaxin.common.Entity.FindSearchBean;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.CommonWebActivity;
import com.huaxin.hxcloud.frendcircles.FrendCircleActivity;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.main.contactview.friend.FriendInfoActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FindSearchActivity extends AppCompatActivity implements View.OnClickListener, SearchResultFragment.OnSearchResultItemClickListenner {

    //搜索栏
    @BindView(R.id.search_editTv)
    public EditText mEditTv;

    @BindView(R.id.search_edit_img_hint)
    ImageView mEditSearchIcon;

    @BindView(R.id.search_edit_img_delete)
    public ImageView mEditDeleteBtn;//编辑框中的删除按钮

    @BindView(R.id.search_button)
    public TextView mSearchTv;

    @BindView(R.id.activity_search_content)
    public FrameLayout  mSearchContent;//搜索内容容器
    @BindView(R.id.activity_search_content_hint)
    public LinearLayout mSearchContentHint;//搜索内容提示容器


    @BindView(R.id.activity_search_tag_people)//选择搜索的类型按钮
    public TextView mPeopleTv;
    @BindView(R.id.activity_search_tag_zixun)
    public TextView mZixunTv;
    @BindView(R.id.activity_search_tag_problem)
    public TextView mProblemTv;

    @BindView(R.id.search_edit_img_type1)//选择了搜索类型后显示在输入框中的图标
    public ImageView imgViewType1;
    @BindView(R.id.search_edit_img_type2)
    public ImageView imgViewType2;
    @BindView(R.id.search_edit_img_type3)
    public ImageView imgViewType3;

    private SearchResultFragment searchResultFragment;
    private FragmentManager      fragmentManager;

    private static int type = 0;//搜索的类型，默认为0，即全部搜索，1为搜索人物

    private boolean isCancel = true;//是否可以点击取消返回发现主界面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_search);
        ButterKnife.bind(this);
        initView();
        initFragment();
    }

    private void initView() {

        mEditTv.setHint("大家都在搜");
        mEditTv.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mEditTv.addTextChangedListener(new TextWatcher() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mEditDeleteBtn.setVisibility(View.VISIBLE);
                    mSearchTv.setText("搜索");
                    isCancel = false;
                } else {
                    mEditDeleteBtn.setVisibility(View.GONE);
                    mSearchTv.setText("取消");
                    isCancel = true;
                }
            }

            //可以在这里放即时搜索界面
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 初始化fragment
     */
    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        searchResultFragment = new SearchResultFragment();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_edit_img_delete:
                mEditTv.setText(null);//清空文字
                mEditDeleteBtn.setVisibility(View.GONE);
                break;
            case R.id.search_button:
                //isCancel决定是关闭findSearchActivity还是关闭searchResultFragment
                if (isCancel) {//显示取消
                    //如果是在搜索结果页面，就返回搜索选择界面
                    if (mSearchContent.isShown()) {
                        hideKeyboard();
                        switchFragmentTo(null);
                        showSelectPannel();
                        type = 0;
                    } else {
                        hideKeyboard();
                        finish();
                    }
                } else {//显示搜索按钮
                    String string = mEditTv.getText().toString().trim();
                    if (TextUtils.isEmpty(string)) {
                        return;
                    }
                    //根据不同的搜索类型请求数据
                    switchFragmentTo(searchResultFragment);
                    searchResultFragment.requestDatas(type, string);
                    hideKeyboard();
                    hideSelectPannel(type);
                }
                break;
            case R.id.activity_search_tag_people:
                type = 1;
                hideSelectPannel(type);
                break;
            case R.id.activity_search_tag_zixun:
                type = 2;
                hideSelectPannel(type);
                break;
            case R.id.activity_search_tag_problem:
                type = 3;
                hideSelectPannel(type);
                break;
        }
    }

    /**
     * 点击了人物或问题或资讯按钮时隐藏其显示
     *
     * @param type：点击的搜索的类型，默认为0
     */
    private void hideSelectPannel(int type) {
        mSearchContentHint.setVisibility(View.GONE);
        //显示搜索内容的容器
        mSearchContent.setVisibility(View.VISIBLE);
        mEditSearchIcon.setVisibility(View.GONE);//隐藏放大镜
        switch (type) {
            case 1:
                imgViewType1.setVisibility(View.VISIBLE);
                imgViewType2.setVisibility(View.GONE);
                imgViewType3.setVisibility(View.GONE);
                break;
            case 2:
                imgViewType1.setVisibility(View.GONE);
                imgViewType2.setVisibility(View.VISIBLE);
                imgViewType3.setVisibility(View.GONE);
                break;
            case 3:
                imgViewType1.setVisibility(View.GONE);
                imgViewType2.setVisibility(View.GONE);
                imgViewType3.setVisibility(View.VISIBLE);
                break;
            default:
                imgViewType1.setVisibility(View.GONE);
                imgViewType2.setVisibility(View.GONE);
                imgViewType3.setVisibility(View.GONE);
                break;
        }
    }

    private void showSelectPannel() {
        mSearchContentHint.setVisibility(View.VISIBLE);
        //显示搜索内容的容器
        mSearchContent.setVisibility(View.GONE);
        //显示放大镜
        mEditSearchIcon.setVisibility(View.VISIBLE);

        imgViewType1.setVisibility(View.GONE);
        imgViewType2.setVisibility(View.GONE);
        imgViewType3.setVisibility(View.GONE);
    }

    //切换fragment
    private void switchFragmentTo(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //如果是空，意味着返回到搜索选择的主界面
        if (fragment == null) {
            searchResultFragment.clearData();
            transaction.hide(searchResultFragment);
            return;
        } else {
            if (fragment.isAdded()) {
                transaction.show(fragment);
            } else {
                transaction.add(R.id.activity_search_content, fragment);
            }
        }
        transaction.commit();
    }


    /**
     * 隐藏键盘
     */
    private void hideKeyboard() {
        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(mEditTv.getWindowToken(), 0);
    }

    @Override
    public void onBackPressed() {
        //如果在显示搜索的内容的情况下，按下返回键隐藏搜索内容
        if (mSearchContent.isShown()) {
            switchFragmentTo(null);
            showSelectPannel();
            return;
        }
        super.onBackPressed();
    }

    /**
     * 当搜索结果出来之后,点击每一个item的回调事件
     *
     * @param type:1是人物，2是咨询，3是问题
     * @param resultBean：点击的item的对象
     * @param position：点击的位置
     */
    @Override
    public void onItemClick(int type, FindSearchResultBean resultBean, int position) {
        switch (type) {
            case 1:
                FindSearchBean.UserArrayBean user = resultBean.getUser();
               /*Intent intent1 = new Intent(this, FindUserActivity.class);
                intent1.putExtra("nickName", user.getNickname());
                intent1.putExtra("icon", user.getImg());
                intent1.putExtra("id", user.getId());
                startActivity(intent1);*/

                goToUserInfoActivity(FindSearchActivity.this, user.getId() + "");

                break;
            case 2:
                FindSearchBean.InformationArrayBean information = resultBean.getInformation();
                String title = information.getTitle();
                String url = information.getUrl();
                Intent intent2 = new Intent(this, CommonWebActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(Constants.TITLE_KEY, title);
                bundle.putString(Constants.URL_KEY, url);
                intent2.putExtras(bundle);
                startActivity(intent2);
                break;
            case 3:
                FindSearchBean.QuestionArrayBean question = resultBean.getQuestion();
                FindInfo.QuestionListBean questionListBean = progressData(question);
                Intent intent3 = new Intent(this, FrendCircleActivity.class);
                Bundle bundle3 = new Bundle();
                bundle3.putSerializable("user", questionListBean);
                intent3.putExtras(bundle3);
                startActivity(intent3);
                break;
        }
    }

    /**
     * 跳转到个人中心界面
     *
     * @param userid
     */
    private void goToUserInfoActivity(Activity activity, String userid) {

        Intent intent = new Intent(activity, FriendInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(ImConstants.CLIENT_ID, userid);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    /**
     * 将搜索到的问题数据处理后再跳转到评论的activity
     */
    private FindInfo.QuestionListBean progressData(FindSearchBean.QuestionArrayBean questionArrayBean) {

        FindInfo.QuestionListBean questionListBean = new FindInfo.QuestionListBean();
        //收藏、关注、点赞
        questionListBean.setIsCollection(questionArrayBean.isIsCollection());
        questionListBean.setIsLike(questionArrayBean.isIsLike());
        questionListBean.setIsFan(questionArrayBean.isIsFan());

        questionListBean.setCollectionNum(questionArrayBean.getCollectionNum());
        questionListBean.setLikeerNum(questionArrayBean.getLikeerNum());

        questionListBean.setCommentNum(questionArrayBean.getCommentNum());
        questionListBean.setContent(questionArrayBean.getContent());
        questionListBean.setImgUrls(questionArrayBean.getImgUrls());
        //        questionListBean.setPublishDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        //                .format(new Date(questionArrayBean.getPublishDate())));
        questionListBean.setPublishDate("" + questionArrayBean.getPublishDate());

        questionListBean.setPublisher(new FindInfo.QuestionListBean.Publisher(
                questionArrayBean.getPublisher().getImg(),
                questionArrayBean.getPublisher().getId(),
                questionArrayBean.getPublisher().getNickName()));
        questionListBean.setQuestionId(questionArrayBean.getQuestionId());
        List<FindSearchBean.QuestionArrayBean.LikeerArrayBean> likeerArray = questionArrayBean
                .getLikeerArray();
        int count = 0;
        if (likeerArray != null)
            count = likeerArray.size();
        List<FindInfo.LikeerArrayBean> beanList = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            FindInfo.LikeerArrayBean likeerArrayBean = new FindInfo.LikeerArrayBean(
                    likeerArray.get(i).getImg(), likeerArray.get(i).getNickName(), likeerArray.get(i).getId()
            );
            beanList.add(likeerArrayBean);
        }
        questionListBean.setLikeerArray(beanList);
        return questionListBean;
    }
}
